<template>
	<div class="card-fill layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<el-form ref="formRef" :model="state.vmModel" label-width="100px">
				<el-row>
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item
							ref="OldPhone_FormItem"
							prop="OldPhone"
							:label="$t('message._system.user.oldPhone')"
							:rules="[
								{
									required: true,
									message: $t('message._system.common.vm.input', { input: $t('message._system.user.oldPhone') }),
									trigger: 'blur',
								},
								{
									pattern: /^1[3-9]\d{9}$/,
									message: $t('message._system.user.phoneError'),
									trigger: 'blur',
								},
							]"
						>
							<el-input v-model="state.vmModel.OldPhone" :placeholder="$t('message._system.user.oldPhonePlaceholder')" clearable></el-input>
						</el-form-item>

						<el-form-item
							ref="NewPhone_FormItem"
							prop="Mobile"
							:label="$t('message._system.user.newPhone')"
							:rules="[
								{
									required: true,
									message: $t('message._system.common.vm.input', { input: $t('message._system.user.newPhone') }),
									trigger: 'blur',
								},
								{
									pattern: /^1[3-9]\d{9}$/,
									message: $t('message._system.user.phoneError'),
									trigger: 'blur',
								},
							]"
						>
							<el-input v-model="state.vmModel.Mobile" :placeholder="$t('message._system.user.newPhonePlaceholder')" clearable></el-input>
						</el-form-item>
						<el-form-item
							ref="Code_FormItem"
							prop="Code"
							:label="$t('message._system.user.code')"
							:rules="[
								{
									required: true,
									message: $t('message._system.common.vm.input', { input: $t('message._system.user.code') }),
									trigger: 'blur',
								},
							]"
						>
							<div class="verification-code">
								<el-input v-model="state.vmModel.Code" :placeholder="$t('message._system.user.codePlaceholder')" clearable></el-input>
								<el-button type="primary" :disabled="state.countdown > 0" @click="getVerificationCode" class="code-button">
									{{ state.countdown > 0 ? `${state.countdown}s` : $t('message._system.user.getCode') }}
								</el-button>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<footer class="el-dialog__footer" style="padding: unset; padding-top: 10px">
				<span class="dialog-footer">
					<el-button type="primary" @click="onSubmit">{{ $t('message._system.common.vm.submit') }}</el-button>
					<el-button @click="onCancel">{{ $t('message._system.common.vm.cancel') }}</el-button>
				</span>
			</footer>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="updatePhone">
import { ElMessage } from 'element-plus';
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import loginApi from '/@/api/login';
import other from '/@/utils/other';

const emit = defineEmits(['refresh', 'closeDialog']);

// 定义变量内容
const formRef = ref();
const state = reactive({
	vmModel: {
		OldPhone: '',
		Code: '',
		Mobile: '',
	},
	countdown: 0,
});

const ci = getCurrentInstance() as any;

// 保存倒计时状态到localStorage
const saveCountdownState = (mobile: string, endTime: number) => {
	localStorage.setItem(
		'updatePhoneCountdown',
		JSON.stringify({
			mobile,
			endTime,
		})
	);
};

// 从localStorage恢复倒计时状态
const restoreCountdownState = () => {
	const savedState = localStorage.getItem('updatePhoneCountdown');
	if (savedState) {
		const { mobile, endTime } = JSON.parse(savedState);
		const now = Date.now();
		if (now < endTime) {
			state.vmModel.Mobile = mobile;
			state.countdown = Math.ceil((endTime - now) / 1000);
			const timer = setInterval(() => {
				state.countdown--;
				if (state.countdown <= 0) {
					clearInterval(timer);
					localStorage.removeItem('updatePhoneCountdown');
				}
			}, 1000);
		} else {
			localStorage.removeItem('updatePhoneCountdown');
		}
	}
};

// 获取验证码
const getVerificationCode = async () => {
	const phone = state.vmModel.Mobile;

	if (!phone) {
		ElMessage.warning(ci.proxy.$t('message._system.user.newPhonePlaceholder'));
		return;
	}
	if (!/^1[3-9]\d{9}$/.test(phone)) {
		ElMessage.warning(ci.proxy.$t('message._system.user.phoneError'));
		return;
	}

	try {
		const res = await loginApi().sendVerificationCode(phone, 'changeMobile', state.vmModel.OldPhone);
		if (res.Code === 200) {
			ElMessage.success(ci.proxy.$t('message._system.user.codeSent'));
			state.countdown = 60;
			const endTime = Date.now() + state.countdown * 1000;
			saveCountdownState(phone, endTime);
			const timer = setInterval(() => {
				state.countdown--;
				if (state.countdown <= 0) {
					clearInterval(timer);
					localStorage.removeItem('updatePhoneCountdown');
				}
			}, 1000);
		} else {
			ElMessage.warning(res.Message);
		}
	} catch (error) {
		ElMessage.error(ci.proxy.$t('message._system.user.codeSendFailed'));
	}
};

// 在组件挂载时恢复倒计时状态
onMounted(() => {
	restoreCountdownState();
});

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 取消
const onCancel = () => {
	closeDialog();
};

// 提交
const onSubmit = () => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loginApi()
				.updatePhone(state.vmModel)
				.then((response) => {
					if (response.Code === 200) {
						ElMessage.success(response.Message);
						closeDialog();
					} else {
						ElMessage.warning(response.Message);
					}
				})
				.catch((error: any) => {
					other.setFormError(ci, error);
				});
		}
	});
};

// 暴露变量
defineExpose({});
</script>

<style lang="scss" scoped>
.verification-code {
	display: flex;
	gap: 12px;

	.el-input {
		flex: 1;
	}

	.code-button {
		width: 120px;
		height: 40px;
		border-radius: 4px;
		font-size: 14px;
		padding: 0;
		transition: all 0.3s ease;

		&:not(:disabled):hover {
			transform: translateY(-1px);
			box-shadow: 0 2px 8px rgba(var(--el-color-primary-rgb), 0.3);
		}

		&:disabled {
			opacity: 0.7;
			cursor: not-allowed;
		}
	}
}

.dialog-footer {
	display: flex;
	justify-content: center;
	gap: 12px;
}
</style>
